package com.td.core.obj.unit;

import java.util.LinkedList;

import com.td.core.obj.TDMap;
import com.td.core.obj.TDObject;
import com.td.core.obj.TDPoint;
import com.td.core.obj.TDRealObject;
import com.td.core.obj.movement.Moveable;
import com.td.core.obj.movement.Movement;
import com.td.core.obj.utils.PointConverter;
import com.td.core.obj.utils.TDVector;

public class Unit extends TDRealObject implements Moveable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
		
	private float speed;
	
	private transient Movement movement;
	
	private float size;
	
	private float life;
	
	private boolean dead;
	
	private float award;
	
	protected final static float REAL_SIZE = 20;
	
	
	public Unit(int x, int y) {
		super(x, y);
			
		size = REAL_SIZE;		
	}
	
	public Unit(TDPoint position) {
		this(position.getX(), position.getY());
	}
	
	public Unit(Unit unit) {	
		this(new TDPoint(unit.getPosition().getX(), unit.getPosition().getY()));
		this.setRealPosition(new TDVector(unit.getRealPosition()));
		this.life = unit.life;
		this.dead = unit.dead;
		this.setRotation(unit.getRotation());
		
	}

	@Override
	public void move() {
		if(movement == null)
			return;
		
		
		TDVector mov = movement.calculate(getRealPosition());
		if(mov != null) {
			
			setRotation((float) movement.getRotation());
			setRealPosition(getRealPosition().add(mov));
		   	setPosition(PointConverter.toTDPoint(getRealPosition()));
			
		}
	   	 		
	}
	
	public void setPath(LinkedList<TDPoint> path) {
		
		LinkedList<TDVector> pathTDVector = new LinkedList<TDVector>();
		for(TDPoint tdPoint : path)
			pathTDVector.add(PointConverter.toTDVector(tdPoint));
				
		movement = new Movement(speed, pathTDVector);
		movement.setStepScale(10);
		movement.setMinDistanceToNextPoint(TDMap.DrawParams.FIELD_SIZE);
	}
	
	public float getSpeed() {
		return speed;
	}

	public void setSpeed(float speed) {
		this.speed = speed;
	}

	public void setLife(float life) {
		this.life = life;
	}

	public void setAward(float award) {
		this.award = award;
	}

	public float getAward() {
		return award;
	}
	
	public float getSize() {
		return size;
	}
	
	public void deacreaseLife(int dLife) {
		this.life -= dLife;
		if(this.life <= 0)
			dead = true;
	}
	
	public boolean isDead() {
		return dead;
	}
	
	public float getLife() {
		return life;
	}
	
	@Override
	public synchronized void copyTo(TDObject obj) {
		
		synchronized (obj) {
			
			if(obj instanceof Unit) {
			
				Unit u = (Unit)obj;
			
				u.setPosition(this.getPosition());
				u.setRealPosition(new TDVector(this.getRealPosition()));
				u.life = this.life;
				u.dead = this.dead;
				u.setRotation(this.getRotation());
			}
			
		}
		
		
	}

	@Override
	public TDObject getCopy() {
		return new Unit(this);
	}
}
